import { defineStore } from 'pinia'

import { jwtDecode } from "jwt-decode"

const name = 'JSON_WEB_TOKEN';

export const useLoginedStore = defineStore("logined", {
    state: () => {
        return { 
            value: Boolean(localStorage.getItem(name))
        }
    },
    getters: {
        logined: state => {
            return state.value
        },
        token: () => {
            // 返回从 localStorage 中获取到的 token   
            return localStorage.getItem(name)
        },
        user: () => {
            // 从 localStorage 中获取到的 token
            const token = localStorage.getItem(name);
            // 解析 token 并从其中获取 payload (载荷)
            const payload = jwtDecode(token);
            return payload;
        }
    },
    actions: {
        set(token) {
            // 将 TOKEN 设置到 localStorage 中
            localStorage.setItem(name, token);
            // 此时可以视为用户已登录，因此将状态修改为 true
            this.value = true;
        },
        remove() {
            // 将 TOKEN 从 localStorage 删除
            localStorage.removeItem(name);
            // 此时可以视为用户退出登录，将状态修改为 false
            this.value = false;
        }
    }
});